<?php
/**
 * Created by mww
 * User: mww
 */

namespace app\admin\controller;
use think\Db;
use think\Request;

class Meet extends Base
{
    /**
     * 首页
     */
    public function index(){
        if(request()->isAjax()){
            extract(input());
            $where = [
                'm_del' => 1
            ];
            if(session("company_id") > 0){
                $where['m_c_id'] = session("company_id");
            }
            if(isset($user_name) && $user_name != ''){
                $where['m_name'] = ['like', '%' . $user_name . '%'];
            }
            if(isset($m_type) && $m_type != ''){
                $where['m_type'] = $m_type;
            }
            if(isset($m_status) && $m_status != ''){
                $where['m_status'] = $m_status;
            }
            //开始时间查询
            if(isset($start) && $start != "" && isset($end) && $end == "")
            {
                $where['m_start'] = ['>=',$start];
            }
            if(isset($end) && $end != "" && isset($start) && $start == "")
            {
                $where['m_start'] = ['<=',$end];
            }
            if(isset($start) && $start != "" && isset($end) && $end != "")
            {
                $where['m_start'] = ['between',[$start,$end]];
            }
            //结束时间查询
            if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend == "")
            {
                $where['m_time'] = ['>=',$loginstart];
            }
            if(isset($loginend) && $loginend != "" && isset($loginstart) && $loginstart == "")
            {
                $where['m_time'] = ['<=',$loginend];
            }
            if(isset($loginstart) && $loginstart != "" && isset($loginend) && $loginend != "")
            {
                $where['m_time'] = ['between',[$loginstart,$loginend]];
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'm.*,user_username,user_phone,c_name';
            $count = Db::table('up_meeting')->alias('m')
                ->join('up_u_user u','m.m_user_id = u.user_id','left')
                ->join('up_company c','u.user_hospital = c.c_id','left')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_meeting')->alias('m')
                ->join('up_u_user u','m.m_user_id = u.user_id','left')
                ->join('up_company c','u.user_hospital = c.c_id','left')
                ->where($where)
                ->page($NowPage,$limits)
                ->order('m_status asc,m_update desc')
                ->field($field)
                ->select();
            if($lists){
                //$week_array = ["周日","周一","周二","周三","周四","周五","周六"];
                foreach ($lists as $k=>$v){
                    //已报名
                    $lists[$k]['users'] = Db::table('up_meeting_user')
                        ->where('mu_m_id',$v['m_id'])
                        ->where('mu_status',2)
                        ->count();
                    //已参会
                    $lists[$k]['joins'] = Db::table('up_meeting_user')
                        ->where('mu_m_id',$v['m_id'])
                        ->where('mu_status',2)
                        ->where('mu_join',2)
                        ->count();
                    //.$week_array[date('w',strtotime($v['m_end']))]
                    $lists[$k]['start_end'] = substr($v['m_start'],0,16).' '.$v['m_week'].' 至 '.substr($v['m_end'],0,16);
                    $lists[$k]['userinfo'] = '姓名('.$v['user_username'] . ')，电话(' . $v['user_phone'] . ')，所属企业(' . $v['c_name'] . ')';
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function meetDel(){
        $m_id = input('id');
        $res = Db::table('up_meeting')->where('m_id',$m_id)->setField('m_del',2);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    /**
     * 添加
     * @return mixed|\think\response\Json
     */
    public function addMeet(){
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            if($m_start >= $m_end){
                return json(['code'=>0,'msg'=>'开始时间和结束时间有问题']);
            }
            if(substr($m_start,0,10) != substr($m_end,0,10)){
                return json(['code'=>0,'msg'=>'会议不能跨天']);
            }
            if($m_start <= $today){
                return json(['code'=>0,'msg'=>'开始时间不能小于当前时间']);
            }
            $week_array = ["周日","周一","周二","周三","周四","周五","周六"];
            $data = array();
            $data['m_id'] = $this->uuid();
            $data['m_number'] = time() . rand(100000,999999);
            $data['m_name'] = $m_name;
            $data['m_type'] = $m_type;
            $data['m_c_id'] = $m_c_id;
            $data['m_user_id'] = $m_user_id;
            $data['m_status'] = 1;
            $data['m_start'] = $m_start;
            $data['m_end'] = $m_end;
            $data['m_day'] = substr($m_start,0,10);
            $data['m_week'] = $week_array[date('w',strtotime($m_start))];
            $data['m_month'] = substr($m_start,0,7);
            $data['m_time'] = $today;
            $data['m_update'] = $today;
            $data['m_desc'] = $m_desc;
            $data['m_img'] = $m_img;
            $data['m_from'] = 3;
            if($data['m_start'] <= $today){
                $data['m_status'] = 2;
            }
            if($data['m_type'] != 2){
                if(!$m_address || !$m_cp_id){
                    return json(['code'=>0,'msg'=>'地址和产品不能为空']);
                }
                $data['m_address'] = $m_address;
                $data['m_cp_id'] = $m_cp_id; //Sae里有获取产品的方法
            }
            if($data['m_type'] != 3){
                if($data['m_type'] == 1) $data['m_files'] = $m_files;
                if($data['m_type'] == 2) $data['m_files'] = $m_files2;
            }
            if($data['m_type'] == 2){
                $m_nums = (int)$m_nums;
                if($m_nums <= 0){
                    return json(['code'=>0,'msg'=>'人数不能低于0']);
                }
                $data['m_nums'] = $m_nums;
                $data['m_upload'] = $m_upload;
            }
            Db::startTrans();
            try {
                $meetid = $data['m_id'];
                Db::table('up_meeting')->insert($data);
                //-----------------
                $meet_u = [
                    'mu_m_id' => $meetid,
                    'mu_user_id' => $m_user_id,
                    'mu_status' => 2,
                    'mu_auth' => 3,
                    'mu_time' => $today,
                    'mu_verify_time' => $today,
                    'mu_update' => $today,
                ];
                Db::table('up_meeting_user')->insert($meet_u);
                Db::commit();
                if($m_type != 2){
                    $cp_name = Db::table('up_company_product')->where('cp_id',$m_cp_id)->value('cp_name');
                    $hour = round((strtotime($m_start)-time())/3600,1);
                    $content = '平台为您发布了'.$cp_name.'产品的'.$m_name.'会议，会议在'.$hour.'小时之后开始，请知悉：';
                    //
                    allInNotice('会议发布提醒',$content,2,$m_user_id,$meetid);
                }

                return json(['code'=>200,'msg'=>'新建成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code'=>0,'msg'=>'新建失败，请刷新测试']);
            }
        }
        $where = [
            'c_verify' => 2,
            'c_status' => 1
        ];
        if(session("company_id") > 0){
            $where['c_id'] = session("company_id");
        }
        $coms = Db::table('up_company')
            ->where($where)
            ->field('c_id,c_name')
            ->select();
        $this->assign('coms',$coms);
        return $this->fetch('meet/add');
    }
    /**
     * 编辑
     * @return mixed|\think\response\Json
     */
    public function meetEdit(){
        if(Request::instance()->isPost()){
            extract(input());
            $today = date('Y-m-d H:i:s');
            if($m_start >= $m_end){
                return json(['code'=>0,'msg'=>'开始时间和结束时间有问题']);
            }
            if(substr($m_start,0,10) != substr($m_end,0,10)){
                return json(['code'=>0,'msg'=>'会议不能跨天']);
            }
            if($m_start <= $today){
                return json(['code'=>0,'msg'=>'开始时间不能小于当前时间']);
            }
            $meet_data = Db::table('up_meeting')->where('m_id',$m_id)->find();
            if($meet_data['m_status'] == 1){
                $week_array = ["周日","周一","周二","周三","周四","周五","周六"];
                $data = array();
                $data['m_name'] = $m_name;
                $data['m_user_id'] = $m_user_id;
                $data['m_c_id'] = $m_c_id;
                $data['m_status'] = 1;
                $data['m_start'] = $m_start;
                $data['m_end'] = $m_end;
                $data['m_day'] = substr($m_start,0,10);
                $data['m_week'] = $week_array[date('w',strtotime($m_start))];
                $data['m_month'] = substr($m_start,0,7);
                $data['m_update'] = $today;
                $data['m_desc'] = $m_desc;
                $data['m_img'] = $m_img;
                if($data['m_start'] <= $today){
                    $data['m_status'] = 2;
                }
                if($meet_data['m_type'] != 2){
                    if(!$m_address || !$m_cp_id){
                        return json(['code'=>0,'msg'=>'地址和产品不能为空']);
                    }
                    $data['m_address'] = $m_address;
                    $data['m_cp_id'] = $m_cp_id; //Sae里有获取产品的方法
                }
                if($meet_data['m_type'] != 3){
                    if($meet_data['m_type'] == 1) $data['m_files'] = $m_files;
                    if($meet_data['m_type'] == 2) $data['m_files'] = $m_files2;
                }
                if($meet_data['m_type'] == 2){
                    $m_nums = (int)$m_nums;
                    if($m_nums <= 0){
                        return json(['code'=>0,'msg'=>'人数不能低于0']);
                    }
                    $data['m_nums'] = $m_nums;
                    $data['m_upload'] = $m_upload;
                }
            }else{
                $data = array();
                $data['m_name'] = $m_name;
                $data['m_update'] = $today;
                $data['m_desc'] = $m_desc;
                $data['m_img'] = $m_img;
                if($meet_data['m_type'] != 3){
                    if($meet_data['m_type'] == 1) $data['m_files'] = $m_files;
                    if($meet_data['m_type'] == 2) $data['m_files'] = $m_files2;
                }
                if($meet_data['m_type'] == 2){
                    $data['m_upload'] = $m_upload;
                }
            }

            Db::startTrans();
            try {
                Db::table('up_meeting')->where('m_id',$m_id)->update($data);
                //-----------------
                if($meet_data['m_status'] == 1 && $meet_data['m_user_id'] != $m_user_id){
                    Db::table('up_meeting_user')
                        ->where('mu_m_id',$m_id)
                        ->where('mu_auth',3)
                        ->setField('mu_user_id',$m_user_id);
                }
                Db::commit();
                $this->editLikes(3,$m_id);
                return json(['code'=>200,'msg'=>'编辑成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code'=>0,'msg'=>'编辑失败，请刷新测试']);
            }
        }
        $m_id = input('m_id');
        $info = Db::table('up_meeting')
            ->where('m_id',$m_id)
            ->find();
        $c_id = $info['m_c_id'];
        //
        $where = [
            'c_verify' => 2,
            'c_status' => 1
        ];
        if(session("company_id") > 0){
            $where['c_id'] = session("company_id");
        }
        $coms = Db::table('up_company')
            ->where($where)
            ->field('c_id,c_name')
            ->select();
        $product = Db::table('up_company_product')
            ->where('cp_c_id',$c_id)
            ->where('cp_status',1)
            ->field('cp_id,cp_name')
            ->order('cp_update desc')
            ->select();
        $users = Db::table('up_u_user')
            ->where('user_hospital',$c_id)
            ->where('user_status',1)
            ->where('user_verify',2)
            ->field('user_id,user_username,user_phone')
            ->order('user_auth desc')
            ->select();
        $this->assign([
            'c_id' => $c_id,
            'info' => $info,
            'coms' => $coms,
            'product' => $product,
            'users' => $users
        ]);
        return $this->fetch('meet/edit');
    }
    /**
     * 会议详情
     * @return mixed|\think\response\Json
     */
    public function meetInfo(){
        $m_id = input('m_id');
        $info = Db::table('up_meeting')->alias('m')
            ->join('up_u_user u','m.m_user_id = u.user_id','left')
            ->join('up_company_product cp','m.m_cp_id = cp.cp_id','left')
            ->join('up_company c','m.m_c_id = c.c_id','left')
            ->where('m_id',$m_id)
            ->field('m.*,user_username,user_phone,cp_name,c_name')
            ->find();
        if($info['m_img']){
            $info['m_img'] = explode(',',$info['m_img']);
        }else{
            $info['m_img'] = [];
        }
        $meet_type = [
            1 => '线上会议',
            2 => '孚玛会议',
            3 => '线下会议',
        ];
        $meet_status = [
            1 => '未开始',
            2 => '进行中',
            3 => '已结束',
        ];
        $meet_from = [
            1 => '业务员',
            2 => '企业负责人',
            3 => '平台',
        ];
        //已报名
        $info['users'] = Db::table('up_meeting_user')
            ->where('mu_m_id',$info['m_id'])
            ->where('mu_status',2)
            ->count();
        //已参会
        $info['joins'] = Db::table('up_meeting_user')
            ->where('mu_m_id',$info['m_id'])
            ->where('mu_status',2)
            ->where('mu_join',2)
            ->count();
        $this->assign([
            'info' => $info,
            'meet_status' => $meet_status,
            'meet_from' => $meet_from,
            'meet_type' => $meet_type
        ]);
        return $this->fetch('meet/meetinfo');
    }
    //-------------------------------------提问和讨论-------------------------------------------
    /**
     * 提问
     * @return mixed|\think\response\Json
     */
    public function question(){
        if(request()->isAjax()){
            extract(input());
            $where = [];
            $where['mq_m_id'] = session('m_id');
            $where['mq_who'] = 0;
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_meeting_question')->alias('mq')
                ->join('up_u_user u','mq.mq_user_id = u.user_id','left')
                ->group('mq_user_id')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_meeting_question')->alias('mq')
                ->join('up_u_user u','mq.mq_user_id = u.user_id','left')
                ->where($where)
                ->group('mq_user_id')
                ->page($NowPage,$limits)
                ->field('mq.*,user_username,user_id,user_image,user_phone')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $m_id = input('m_id');
        session('m_id', $m_id);
        return $this->fetch();
    }
    /**
     * 查看问题
     * @return mixed|\think\response\Json
     */
    public function seeReplys(){
        $user_id = input('user_id');
        $where = [
            'mq_user_id|mq_who' => $user_id,
            'mq_m_id' => session('m_id')
        ];
        $field = 'mq.*,user_username,user_image,user_type,user_phone';
        $reply = Db::table('up_meeting_question')->alias('mq')
            ->join('up_u_user u','mq.mq_user_id = u.user_id','left')
            ->where($where)
            ->order('mq_time asc')
            ->field($field)
            ->select();
        $this->assign([
            'reply' => $reply
        ]);
        return $this->fetch('meet/reply');
    }
    /**
     * 查看讨论
     * @return mixed|\think\response\Json
     */
    public function seeTalks(){
        $where = [
            'mt_m_id' => input('m_id')
        ];
        $field = 'mt.*,user_username,user_image,user_type,user_phone';
        $reply = Db::table('up_meeting_talk')->alias('mt')
            ->join('up_u_user u','mt.mt_user_id = u.user_id','left')
            ->where($where)
            ->order('mt_time asc')
            ->field($field)
            ->select();
        $this->assign([
            'reply' => $reply
        ]);
        return $this->fetch('meet/talk');
    }
}